<script setup>
import { ref, onMounted } from 'vue'
import { fetchGoodsTypeList, deleteGoodsType } from '@/api/goods'
import AddGoodsType from './components/AddGoodsType.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import logger from '@/utils/logger'
import { formatDateTime } from '@/utils/dayjs'

// 对话框
const dialogVisible = ref(false)
const currentGoodsType = ref(null)

// 列表 & 分页
const tableData = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 查询字段
const queryFields = ref({
  goodsTypeName: '',
})

// 打开新增
const openAddDialog = () => {
  currentGoodsType.value = null
  dialogVisible.value = true
}

// 打开编辑
const openEditDialog = (row) => {
  currentGoodsType.value = JSON.parse(JSON.stringify(row))
  dialogVisible.value = true
}

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false
}

// 获取数据
const fetchGoodsTypeData = async () => {
  try {
    loading.value = true
    const params = {
      currentPage: currentPage.value,
      pageSize: pageSize.value,
      queryFields: {
        goodsTypeName: queryFields.value.goodsTypeName.trim() || null,
      },
    }
    const res = await fetchGoodsTypeList(params)
    if (res.success && res.data) {
      // 后端返回格式与商品列表保持一致 { list: [], total: 0 }
      if (Array.isArray(res.data)) {
        // 兼容老接口直接返回数组
        tableData.value = res.data
        total.value = res.data.length
      } else {
        tableData.value = res.data.list || []
        total.value = res.data.total || 0
      }
    } else {
      tableData.value = []
      total.value = 0
      ElMessage.error(res.msg || '获取商品类别失败')
    }
  } catch (error) {
    logger.error('获取商品类别失败', error)
    ElMessage.error('获取商品类别失败')
  } finally {
    loading.value = false
  }
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除商品类别 '${row.dealerGoodsTypeName}' 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    loading.value = true
    const res = await deleteGoodsType(row.dealerGoodsTypeId)
    if (res.success) {
      ElMessage.success('删除成功')
      await fetchGoodsTypeData()
    }
  } catch (error) {
    if (error !== 'cancel') {
      logger.error('删除商品类别失败', error)
      ElMessage.error('删除商品类别失败')
    }
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchGoodsTypeData()
}

// 重置
const resetSearch = () => {
  queryFields.value.goodsTypeName = ''
  currentPage.value = 1
  fetchGoodsTypeData()
}

onMounted(() => {
  currentPage.value = 1
  fetchGoodsTypeData()
})

// 分页事件
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchGoodsTypeData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchGoodsTypeData()
}
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="currentGoodsType ? '编辑商品标签' : '添加商品标签'"
    width="50%"
    destroy-on-close
    align-center
    @close="closeDialog"
  >
    <AddGoodsType
      :initial-data="currentGoodsType"
      @success="fetchGoodsTypeData"
      @close="closeDialog"
    />
  </el-dialog>

  <div class="main-container">
    <div class="controller-container">
      <div class="controller-item">
        <el-form :inline="true" :model="queryFields">
          <el-form-item label="类别名称">
            <el-input
              v-model="queryFields.goodsTypeName"
              placeholder="请输入类别名称"
              clearable
              style="width: 240px"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><LineMdSearch /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <template #icon>
                <el-icon><LineMdSearch /></el-icon>
              </template>
              搜索
            </el-button>
            <el-button @click="resetSearch">
              <template #icon>
                <el-icon><LineMdClose /></el-icon>
              </template>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="controller-item">
        <el-form-item>
          <el-button type="primary" @click="openAddDialog">
            <template #icon>
              <el-icon><LineMdPlus /></el-icon>
            </template>
            添加类别
          </el-button>
        </el-form-item>
      </div>
    </div>

    <div class="table-container">
      <el-table v-loading="loading" :data="tableData" style="width: 100%" height="100%">
        <el-table-column
          prop="dealerGoodsTypeCode"
          label="类别编码"
          min-width="120"
          align="center"
        />
        <el-table-column
          prop="dealerGoodsTypeName"
          label="类别名称"
          min-width="120"
          align="center"
        />
        <el-table-column label="创建时间" min-width="160" align="center">
          <template #default="{ row }"> {{ formatDateTime(row.createTime) }} </template>
        </el-table-column>
        <el-table-column label="更新时间" min-width="160" align="center">
          <template #default="{ row }"> {{ formatDateTime(row.updateTime) }} </template>
        </el-table-column>
        <el-table-column prop="createUser" label="创建人" width="100" align="center" />
        <el-table-column label="操作" width="200" fixed="right" align="center">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="openEditDialog(row)">
              <template #icon>
                <el-icon><LineMdEdit /></el-icon>
              </template>
              编辑
            </el-button>
            <el-popconfirm
              placement="top-start"
              confirm-button-text="确定"
              cancel-button-text="取消"
              :title="`确定要删除商品类别 '${row.dealerGoodsTypeName}' 吗？`"
              width="250"
              confirm-button-type="danger"
              @confirm="handleDelete(row)"
            >
              <template #reference>
                <el-button type="danger" size="small">
                  <template #icon>
                    <el-icon><LineMdTrash /></el-icon>
                  </template>
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.main-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  gap: 10px;
  .controller-container {
    border-radius: 10px;
    background-color: #fff;
    .controller-item {
      display: flex;
      align-items: center;
      gap: 10px;
    }
  }
  .table-container {
    flex: 1;
    min-height: 0;
    display: flex;
    flex-direction: column;
    background-color: #fff;
    border-radius: 10px;
    padding: 10px;
    overflow: hidden;

    .el-table {
      flex: 1;
    }
  }
  .pagination-container {
    display: flex;
    justify-content: flex-end;
  }
}
</style>
